package com.mti.zhpt.shared.classHelper;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.mti.zhpt.model.CommandCustomEntity;

import java.util.ArrayList;
import java.util.List;

public class CommandCustomHelper {
    /**
     * @param deptCode
     * @param nodes
     * @Description: 递归处理   数据库树结构数据->树形json
     * @Author: zhaopf@mti-sh.cn
     * @Date: 2019/4/20 0:05
     */
    public static JSONArray getNodeJson(String deptCode, List<CommandCustomEntity> nodes) {


        //当前层级当前点下的所有子节点（数据库不要多查,一次加载到集合然后慢慢处理）
        List<CommandCustomEntity> childList = getChildNodes(deptCode, nodes);

        JSONArray childTree = new JSONArray();
        for (CommandCustomEntity node : childList) {

            JSONObject o = new JSONObject();
            o.put("id", node.getId());
            o.put("deptName", node.getDeptName());
            o.put("deptCode", node.getDeptCode());
            o.put("mobilePhone", node.getMobilePhone());
            o.put("peopleAlways", node.getPeopleAlways());
            JSONArray childs = getNodeJson(node.getDeptCode(), nodes);  //递归调用该方法
            if (!childs.isEmpty()) {
                o.put("children", childs);
            }else {
                o.put("children", null);
            }
            childTree.fluentAdd(o);
        }
        return childTree;
    }


    /**
     * @param nodeId
     * @param nodes
     * @Description: 获取当前节点的所有子节点
     * @Author: zhaopf@mti-sh.cn
     * @Date: 2019/4/20 0:06
     */
    public static List<CommandCustomEntity> getChildNodes(String nodeId, List<CommandCustomEntity> nodes) {
        List<CommandCustomEntity> list = new ArrayList<>();

        for (CommandCustomEntity node : nodes) {
            if (node.getParentCode().equals(nodeId)) {
                list.add(node);
            }
        }
        return list;
    }

}
